import 'dart:io';

import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:image_picker/image_picker.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as path;
import 'package:family_app/src/features/gallery/models/album_model.dart';
import 'package:family_app/src/features/gallery/models/photo_model.dart';
import 'package:family_app/src/features/gallery/services/gallery_service.dart';

/// 相册列表状态提供者
final albumsProvider = FutureProvider<List<AlbumModel>>((ref) async {
  final galleryService = ref.watch(galleryServiceProvider);
  return galleryService.getAlbums();
});

/// 当前选中相册ID提供者
final selectedAlbumIdProvider = StateProvider<String?>((ref) => null);

/// 当前选中相册提供者
final selectedAlbumProvider = FutureProvider<AlbumModel?>((ref) async {
  final galleryService = ref.watch(galleryServiceProvider);
  final albumId = ref.watch(selectedAlbumIdProvider);
  if (albumId == null) return null;
  return galleryService.getAlbum(albumId);
});

/// 相册照片列表提供者
final albumPhotosProvider =
    FutureProvider.family<List<PhotoModel>, String>((ref, albumId) async {
  final galleryService = ref.watch(galleryServiceProvider);
  return galleryService.getPhotos(albumId);
});

/// 相册操作状态提供者
final albumOperationProvider =
    StateNotifierProvider<AlbumOperationNotifier, AlbumOperationState>((ref) {
  final galleryService = ref.watch(galleryServiceProvider);
  return AlbumOperationNotifier(galleryService, ref);
});

/// 相册操作状态管理器
class AlbumOperationNotifier extends StateNotifier<AlbumOperationState> {
  final GalleryService _galleryService;
  final Ref _ref;
  final _imagePicker = ImagePicker();

  AlbumOperationNotifier(this._galleryService, this._ref)
      : super(const AlbumOperationState.initial());

  /// 创建新相册
  Future<AlbumModel?> createAlbum(String name, {String? description}) async {
    state = const AlbumOperationState.loading();
    try {
      final album =
          await _galleryService.createAlbum(name, description: description);
      if (album != null) {
        state = AlbumOperationState.success('相册创建成功');
        // 刷新相册列表
        _ref.invalidate(albumsProvider);
        return album;
      } else {
        state = const AlbumOperationState.error('相册创建失败');
        return null;
      }
    } catch (e) {
      state = AlbumOperationState.error('相册创建失败: ${e.toString()}');
      return null;
    }
  }

  /// 更新相册
  Future<AlbumModel?> updateAlbum(String albumId,
      {String? name, String? description}) async {
    state = const AlbumOperationState.loading();
    try {
      final album = await _galleryService.updateAlbum(albumId,
          name: name, description: description);
      if (album != null) {
        state = AlbumOperationState.success('相册更新成功');
        // 刷新相册列表和当前相册
        _ref.invalidate(albumsProvider);
        _ref.invalidate(selectedAlbumProvider);
        return album;
      } else {
        state = const AlbumOperationState.error('相册更新失败');
        return null;
      }
    } catch (e) {
      state = AlbumOperationState.error('相册更新失败: ${e.toString()}');
      return null;
    }
  }

  /// 删除相册
  Future<bool> deleteAlbum(String albumId) async {
    state = const AlbumOperationState.loading();
    try {
      final success = await _galleryService.deleteAlbum(albumId);
      if (success) {
        state = AlbumOperationState.success('相册删除成功');
        // 刷新相册列表
        _ref.invalidate(albumsProvider);
        // 如果当前选中的相册被删除，清空选中状态
        if (_ref.read(selectedAlbumIdProvider) == albumId) {
          _ref.read(selectedAlbumIdProvider.notifier).state = null;
        }
        return true;
      } else {
        state = const AlbumOperationState.error('相册删除失败');
        return false;
      }
    } catch (e) {
      state = AlbumOperationState.error('相册删除失败: ${e.toString()}');
      return false;
    }
  }

  /// 从相机拍照并添加到相册
  Future<PhotoModel?> takePhotoAndAddToAlbum(String albumId) async {
    state = const AlbumOperationState.loading();
    try {
      // 拍照
      final XFile? image =
          await _imagePicker.pickImage(source: ImageSource.camera);
      if (image == null) {
        state = const AlbumOperationState.initial();
        return null;
      }

      // 复制到应用目录
      final cacheDir = await _galleryService.getImageCacheDir();
      final fileName =
          '${DateTime.now().millisecondsSinceEpoch}_${path.basename(image.path)}';
      final localPath = '$cacheDir/$fileName';
      await File(image.path).copy(localPath);

      // 添加到相册
      final photo = await _galleryService.addPhoto(albumId, localPath);
      if (photo != null) {
        state = AlbumOperationState.success('照片添加成功');
        // 刷新相册列表和照片列表
        _ref.invalidate(albumsProvider);
        _ref.invalidate(albumPhotosProvider(albumId));
        _ref.invalidate(selectedAlbumProvider);
        return photo;
      } else {
        state = const AlbumOperationState.error('照片添加失败');
        return null;
      }
    } catch (e) {
      state = AlbumOperationState.error('照片添加失败: ${e.toString()}');
      return null;
    }
  }

  /// 从相册选择照片并添加到相册
  Future<List<PhotoModel>> pickImagesAndAddToAlbum(String albumId) async {
    state = const AlbumOperationState.loading();
    try {
      // 选择照片
      final List<XFile> images = await _imagePicker.pickMultiImage();
      if (images.isEmpty) {
        state = const AlbumOperationState.initial();
        return [];
      }

      final List<PhotoModel> addedPhotos = [];
      final cacheDir = await _galleryService.getImageCacheDir();

      // 逐个添加照片
      for (final image in images) {
        final fileName =
            '${DateTime.now().millisecondsSinceEpoch}_${path.basename(image.path)}';
        final localPath = '$cacheDir/$fileName';
        await File(image.path).copy(localPath);

        final photo = await _galleryService.addPhoto(albumId, localPath);
        if (photo != null) {
          addedPhotos.add(photo);
        }
      }

      if (addedPhotos.isNotEmpty) {
        state = AlbumOperationState.success('已添加 ${addedPhotos.length} 张照片');
        // 刷新相册列表和照片列表
        _ref.invalidate(albumsProvider);
        _ref.invalidate(albumPhotosProvider(albumId));
        _ref.invalidate(selectedAlbumProvider);
        return addedPhotos;
      } else {
        state = const AlbumOperationState.error('照片添加失败');
        return [];
      }
    } catch (e) {
      state = AlbumOperationState.error('照片添加失败: ${e.toString()}');
      return [];
    }
  }

  /// 删除照片
  Future<bool> deletePhoto(String albumId, String photoId) async {
    state = const AlbumOperationState.loading();
    try {
      final success = await _galleryService.deletePhoto(albumId, photoId);
      if (success) {
        state = AlbumOperationState.success('照片删除成功');
        // 刷新相册列表和照片列表
        _ref.invalidate(albumsProvider);
        _ref.invalidate(albumPhotosProvider(albumId));
        _ref.invalidate(selectedAlbumProvider);
        return true;
      } else {
        state = const AlbumOperationState.error('照片删除失败');
        return false;
      }
    } catch (e) {
      state = AlbumOperationState.error('照片删除失败: ${e.toString()}');
      return false;
    }
  }
}

/// 相册操作状态
class AlbumOperationState {
  final bool isLoading;
  final bool isSuccess;
  final String? message;
  final String? error;

  const AlbumOperationState({
    required this.isLoading,
    required this.isSuccess,
    this.message,
    this.error,
  });

  /// 初始状态
  const AlbumOperationState.initial()
      : isLoading = false,
        isSuccess = false,
        message = null,
        error = null;

  /// 加载中状态
  const AlbumOperationState.loading()
      : isLoading = true,
        isSuccess = false,
        message = null,
        error = null;

  /// 成功状态
  const AlbumOperationState.success(String this.message)
      : isLoading = false,
        isSuccess = true,
        error = null;

  /// 错误状态
  const AlbumOperationState.error(String this.error)
      : isLoading = false,
        isSuccess = false,
        message = null;
}
